<style lang="less">
    .zk-list {
        .ant-table td {
            white-space: nowrap;
        }

        //兼容火狐超出显示...
        // .ant-table-row-cell-ellipsis span{
        //     display: block;
        //     width:100%;
        //     overflow: hidden;
        //     white-space: nowrap;
        //     -o-text-overflow: ellipsis;
        //     text-overflow: ellipsis;
        // }
        .input{
            width: 100%;
        }
        // 优化展示
        .input.ant-calendar-picker{
            & {
                min-width: 100% !important;
            }
            .ant-calendar-picker-input{
                padding-right: 25px;
            }
        }

        &.style1{
            // padding-left: 10px;
        }
        // 定制修改
        .search-interval{
            height: 10px;
            background-color: #fff;
        }

        .table-page-search-wrapper{
            padding:20px;
            padding-top: 0;
            padding-bottom: 6px;
            // box-shadow: 0px 2px 4px 0px rgba(14,97,60,0.08);
        }

        .table-operator{
            margin-bottom: 0;
            padding-left: 20px;
            padding-bottom: 10px;
            padding-top: 10px;
        }
        
        .table-page-search-wrapper .ant-form-item-control .ant-select .ant-select-selection--multiple .ant-select-selection__rendered{
            height: 32px;
            overflow: hidden;
            width: 100%;
            input {
                // visibility: hidden;
            }
            // ul{
            //     display:block;
            //     white-space:nowrap;
            //     overflow:hidden;
            //     white-space:nowrap; 
            //     overflow:hidden; 
            //     text-overflow:ellipsis;
            //     border: 1px solid rebeccapurple;
            // }
            // li {
            //    padding: 0;
            //    background-color: transparent;
            //    border: none;
            // //    padding-top:2px;
            //    height: 100%;
            //    width: 90%;
            //    overflow: hidden;
            // }
            // li{
            //     border: none;
            //     background-color: transparent;
            //     padding: 0;
            //     max-width:300px;
            //     min-width: 128px;
            // }
        }

        .table-page-search-wrapper .ant-form-item-control .ant-select .ant-select-selection--multiple{
            padding-bottom: 0;
        }
    }

    .zk-list.no-data {
        // .ant-table-body::-webkit-scrollbar {
        //     width: 0 !important;
        // }

        .ant-table-placeholder {
            // border-top: none;
        }
        
    }
</style>
<template>
    <a-card :title="listTitle" :bordered="false" class="zk zk-list" :class="{ 'no-data': noData,'style1':type==2 }" :body-style="bodyStyleVal">
        <div class="table-page-search-wrapper" v-if="searchsOpt.length>0">
            <a-form layout="inline">
                <a-row :gutter="48">
                    <a-col v-bind="searchCol" v-for="(item, index) in searchsOpt" :key="item.dataIndex" v-show="(index < 24/searchCol.md-1)|| advanced">
                        <slot v-if="item.scopedSlots" :name="item.scopedSlots.customRender" :item="item"></slot>
                        <a-form-item :label="item.title" v-if="!item.scopedSlots" :colon="false">
                            <a-input v-if="!item.type || item.type == InputTypeEnum.TEXT" v-model="item.value" class="input"/>
                            <a-input-number :ref="item.dataIndex" v-else-if="item.type == InputTypeEnum.NUMBER" v-model="item.value" class="input" />
                            <a-date-picker :ref="item.dataIndex" v-else-if="item.type == InputTypeEnum.DATE" v-model="item.value" class="input" :placeholder="item.placeholder || '请选择时间'" :show-time="false" :value-format="'YYYY-MM-DD'" :format="'YYYY-MM-DD'" />
                            <a-date-picker :ref="item.dataIndex" v-else-if="item.type == InputTypeEnum.DATE_TIME" v-model="item.value" class="input" :placeholder="item.placeholder || '请选择时间'" :show-time="true" :value-format="'YYYY-MM-DD HH:mm:ss'" :format="'YYYY-MM-DD HH:mm:ss'" />
                            <a-time-picker :ref="item.dataIndex" v-else-if="item.type == InputTypeEnum.TIME" v-model="item.value" class="input" :value-format="'HH:mm:ss'" :format="'HH:mm:ss'" :placeholder="item.placeholder || '请选择时间'" />
                            <zk-select :ref="item.dataIndex" v-else-if="item.type == InputTypeEnum.SELECT" v-model="item.value" :placeholder="item.placeholder || '请选择...'" :options="item.options" class="input"></zk-select>
                            <zk-select :ref="item.dataIndex" v-else-if="item.type == InputTypeEnum.SINGLE_SEARCH_SELECT" v-model="item.value" :placeholder="item.placeholder || '请输入...'" :options="item.options" class="input" :hasSearch="true" :freeIn="true" :allowClear="true"></zk-select>
                            <zk-select :ref="item.dataIndex" v-else-if="item.type == InputTypeEnum.MULTIPLE_SEARCH_SELECT" v-model="item.value" :placeholder="item.placeholder || '请输入...'" :options="item.options" class="input" :hasSearch="true" :freeIn="true" :allowClear="true" :mode="'multiple'"></zk-select>
                            <zk-select :ref="item.dataIndex" v-else-if="item.type == InputTypeEnum.MULTIPLE_SELECT" v-model="item.value" :placeholder="item.placeholder || '请选择...'" :options="item.options" class="input" :mode="'multiple'" :maxTagCount="2" :maxTagTextLength="2" :no-tag="true"></zk-select>
                            <ZkArea v-else-if="item.type == InputTypeEnum.AREA" v-model="item.value" :placeholder="item.placeholder || '请选择...'" class="input"></ZkArea>
                            <a-range-picker :ref="item.dataIndex" v-else-if="item.type == InputTypeEnum.RANGE_DATE" v-model="item.value" class="input" :placeholder="item.placeholder || ['开始时间','结束时间']" :show-time="false" :value-format="'YYYY-MM-DD 00:00:00'" :format="'YYYY-MM-DD'" />
                            <a-range-picker :ref="item.dataIndex" v-else-if="item.type == InputTypeEnum.RANGE_DATE_TIME" v-model="item.value" class="input" :placeholder="item.placeholder || ['开始时间','结束时间']" :show-time="true" :value-format="'YYYY-MM-DD HH:mm:ss'" :format="'YYYY-MM-DD HH:mm:ss'" style="width:100%"/>
                            <a-range-picker :mode="['date','date']" :ref="item.dataIndex" v-else-if="item.type == InputTypeEnum.RANGE_MONTH" v-model="item.value" class="input" :placeholder="item.placeholder || ['开始月份','结束月份']" :show-time="false" :value-format="'YYYY-MM'" :format="'YYYY-MM'" />
                            <a-month-picker :ref="item.dataIndex" v-else-if="item.type == InputTypeEnum.MONTH" v-model="item.value" class="input" :placeholder="item.placeholder || '请选择月份'" :show-time="false" :value-format="'YYYY-MM'" :format="'YYYY-MM'" />
                        </a-form-item>
                    </a-col>
                    <a-col v-bind="searchBtns" v-if="searchsOpt.length > 0">
                        <span class="table-page-search-submitButtons" :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}">
                            <a-button type="link" @click="searchFunc(true)">查询</a-button>
                            <a-button type="link" @click="reset()">重置</a-button>
                            <a @click="toggleAdvanced" style="margin-left: 8px" v-if="hasUnfold">
                                {{ advanced ? "收起" : "展开" }}
                                <a-icon :type="advanced ? 'up' : 'down'" />
                            </a>
                        </span>
                    </a-col>
                </a-row>
            </a-form>
        </div>
        <!-- <div class="search-interval" v-if="searchsOpt.length>0"></div> -->
        <div class="table-operator" v-if="$slots.operBtns">
            <slot name="operBtns"></slot>
        </div>
        <slot name="table"></slot>
        <s-table ref="table" name="zk-list-table" size="default" v-bind="$props" :showPagination="showPagination" :data="sourceData" :scroll="vScroll" :columns="vColumns" v-if="useDefaultTable"  @expand="onExpand" >
            <template v-for="item in tableSlots" v-slot:[item.scopedSlots.customRender]="record">
                <slot :name="item.scopedSlots.customRender" v-bind="record"></slot>
            </template>
        </s-table>
    </a-card>
</template>

<script>
    import { Ellipsis, STable } from '@/components'
    import { InputTypeEnum } from './enum'
    import moment from 'moment'
    import ZkSelect from './ZkSelect';
    import ZkArea from './ZkArea.vue';
    import { formatTimeStr } from './utils';
    /**
     * showPagination
     * columns:
     * maxLength 列内容最大长度
     * format = 'YYYY-MM-DD HH:mm:ss' 列数据格式化
     * isSortInput 是否排序输入列
     * emit:
     * saveSortInput(waitSaveSortInput,next)
     * refresh(true) 是否刷新第一页 true:第一页 false:当前页
     */
    export default {
        name: 'ZkList',
        components: {
            STable,
            ZkSelect,
            Ellipsis,
            ZkArea
        },
        props: Object.assign({}, STable.props, {
            /** 列表类型 0. 普通 1. min 型 2.中等大小 */
            type: {
                type: Number,
                default: 0,
            },
            title: {
                type: String,
                default: ()=>null,
            },
            listTitle:{
                type:String,
                default:()=>''
            },
            searchs: {
                type: Array,
                default: () => [],
            },
            data: {
                type: Function,
                required: false,
            },
            scroll: {
                type: Object,
                default: () => ({
                    x: true,
                }),
            },
            // tableLayout:{
            //     type:String,
            //     default:()=>'fixed'
            // }
            // rowSelection:{
            // }
        }),
        created() {
            this.createSearchsOpt()
        },
        data() {
            return {
                InputTypeEnum,
                // 高级搜索 展开/关闭
                advanced: false,
                val: null,
                sourceData: (parameter) => {
                    const queryParams = this.searchsOpt.reduce((res, item) => {
                        let value = item.value;
                        if (typeof item.value !== 'undefined'){
                            // 按照约定,日期作为请求参数时调整为格式 YYYY-MM-DD 00:00:00
                            if (item.type==InputTypeEnum.DATE||item.type==InputTypeEnum.TIME) {
                                if(value)value = formatTimeStr(value);
                            }
                            if (item.type==InputTypeEnum.RANGE_DATE||item.type==InputTypeEnum.RANGE_DATE_TIME||item.type==InputTypeEnum.RANGE_MONTH) {
                                // 调整数组描述的范围时间为两个字段描述
                                if (value) {
                                    res[item.dataIndex] = value[0];
                                    res[item.dataIndex1] = value[1];
                                }else{
                                    res[item.dataIndex] = null;
                                    res[item.dataIndex1] = null;
                                }
                            }else{
                                res[item.dataIndex] = value;
                            }
                        }
                        return res
                    }, {})
                    // 缓存当前查询条件用作请求重现等用途
                    this.nowQueryParams = queryParams
                    this.nowParameter = parameter
                    return this.data(queryParams, parameter).then((res) => {
                        if (res.totalCount < 1 && res.data && res.data.length == 0) {
                            // 总数据量为0 且实际拉取数据也为0
                            this.noData = true
                        } else {
                            this.noData = false
                        }
                        return res
                    })
                },
                /** 是否使用默认表格,未传入表格则使用默认的 */
                useDefaultTable: !this.$slots.table,
                /** 搜索选项配置 */
                searchsOpt: [],
                /** 搜索默认值 */
                searchsDefaultVal: {},
                /** 当前无数据 */
                noData: true,
                /** 当前查询条件 **/
                nowQueryParams: null,
                /** 当前分页条件 **/
                nowParameter: null,
                /** 是否显示排序输入框 */
                showSortInput: false,
                /** 待保存的排序框输入值 */
                waitSaveSortInput:{

                }
            }
        },
        computed: {
            tableSlots() {
                return this.columns.filter(
                    (item) => item.scopedSlots && item.scopedSlots.customRender
                )
            },
            vColumns() {
                return this.columns.map((item) => {
                    if (item.maxLength && !item.customRender) {
                        item.customRender = (text, record, index) => {
                            if (text || text == 0) {
                                return (
                                    <Ellipsis length={item.maxLength * 2} tooltip>
                                        {text}
                                    </Ellipsis>
                                )
                            } else {
                                return ''
                            }
                        }
                    }

                    if (item.format) {
                        item.customRender = (text, record, index) => {
                            return text&&formatTimeStr(text, item.format != true ? item.format : 'YYYY-MM-DD HH:mm:ss');
                        }
                    }

                    if (item.isSortInput) {
                        item.title = () => {
                            const onClick = () => {
                                if (this.showSortInput) {
                                    this.$emit('saveSortInput',this.waitSaveSortInput,() => {
                                        this.showSortInput = false;
                                    });
                                } else {
                                    this.showSortInput = true;
                                }
                            };
                    
                            return (
                                <zk-btn onClick={onClick}>{this.showSortInput ? '[保存]' : '[排序]'}</zk-btn>
                            );
                        }
                        item.customRender = (text, record, index) => this.showSortInput ? (<a-input style="width:100px;margin-right:4px;" value={text} onInput={(e)=>this.onSortInput(record,item.dataIndex,e.target.value)} />) : text;
                    }
                    return item
                })
            },
            bodyStyleVal() {
                if (this.type == 1||this.type == 2) {
                    return {
                        padding: 0,
                    }
                } else {
                    return {
                        padding: 0
                    }
                }
            },
            searchCol() {
                if (this.type == 1) {
                    return {
                        md:12,
                        sm:24  
                    }
                } if (this.type == 2) {
                    return {
                        md:8,
                        sm:24  
                    }
                } else{
                    return {
                        md: 6,
                        sm: 24
                    }
                }
            },
            searchBtns() {
                return {
                    md: (!this.advanced && this.searchCol.md) || 24,
                    sm: 24,
                }
            },
            hasUnfold() {
                if (this.type == 1) {
                    return this.searchsOpt.length > 1
                } else {
                    return this.searchsOpt.length > 3
                }
            },
            vScroll() {
                return this.scroll
            },
        },
        methods: {
            toggleAdvanced() {
                this.advanced = !this.advanced
            },
            createSearchsOpt() {
                this.searchsOpt = this.searchs.map((item) => {
                    if (item.type==InputTypeEnum.SELECT&&!item.value) {
                        // 单选下拉尝试设置 'null' 即全部为默认值
                        item.value = 'null';
                    }
                    this.searchsDefaultVal[item.dataIndex] = item.value || undefined;
                    return {
                        ...item,
                        value: item.value || undefined,
                        placeholder: null
                    }
                })
            },
            /**
             * 刷新
             * @param {boolean} params 是否刷新第一页 true:第一页 false:当前页
             */
            refresh(params) {
                this.showSortInput = false;
                this.$refs.table.refresh(params)
            },
            reset() {
                this.searchsOpt.forEach((item) => {
                    item.value = this.searchsDefaultVal[item.dataIndex];
                })
                this.$emit('onreset');
                setTimeout(() => {
                    this.refresh(true);
                }, 200);
            },
            searchFunc() {
                this.refresh(true);
                this.$emit('onsearch')
            },
            // 跳转至上一页
            prePage() {
                const table = this.$refs.table
                if (table.localPagination) {
                    table.localPagination.current--
                    table.loadData()
                }
            },
            // 跳转至下一页
            nextPage() {
                const table = this.$refs.table
                if (table.localPagination) {
                    table.localPagination.current++
                    table.loadData()
                }
            },
            /** 查询上一行 **/
            queryPreRow,
            /** 查询下一行 **/
            queryNextRow,
            onSortInput,
            onExpand(expanded, record) {
                this.$emit('expand', expanded, record)
            },
        },
    }

    function queryPreRow(id) {
        return new Promise((resolve, reject) => {
            const table = this.$refs.table
            const array = table.localDataSource
            const nowRow = queryNowRow(id, array)
            if (!nowRow) {
                throw Error('当前页未找到该行,id:', id)
            }
            let preRowIndex = nowRow._index - 1
            if (preRowIndex < 0) {
                // 已是首行则尝试从前一页数据读取上一行
                const parameter = Object.assign({}, this.nowParameter)
                parameter.pageNo = parameter.pageNo - 1
                if (parameter.pageNo > 0) {
                    this.data(this.nowQueryParams, parameter).then((res) => {
                        const preRow = res.data[res.data.length - 1]
                        resolve({
                            nowRow,
                            preRow,
                        })
                    })
                } else {
                    resolve({
                        nowRow,
                        preRow: null,
                    })
                }
            } else {
                // 非首行返回上一行数据
                resolve({
                    nowRow,
                    preRow: array[preRowIndex],
                })
            }
        })
    }

    function queryNextRow(id) {
        return new Promise((resolve, reject) => {
            const table = this.$refs.table
            const array = table.localDataSource
            const nowRow = queryNowRow(id, array)
            if (!nowRow) {
                throw Error('当前页未找到该行,id:', id)
            }
            let nextRowIndex = nowRow._index + 1
            if (nextRowIndex > array.length - 1) {
                // 已是尾行则尝试从下一页数据读取
                const parameter = Object.assign({}, this.nowParameter)
                parameter.pageNo = parameter.pageNo + 1
                this.data(this.nowQueryParams, parameter).then((res) => {
                    const nextRow = res.data.length > 0 ? res.data[0] : null
                    resolve({
                        nowRow,
                        nextRow,
                    })
                })
            } else {
                // 非尾行返回下一行数据
                resolve({
                    nowRow,
                    nextRow: array[nextRowIndex],
                })
            }
        })
    }

    /**
     * 通过 Id 查询当前行
     */
    function queryNowRow(id, array) {
        for (let index = 0, len = array.length; index < len; index++) {
            const item = array[index]
            if (item.id == id) {
                item._index = index
                return item
            }
        }
        return null
    }
    /**
     * 排序输入框输入内容
     */
    function onSortInput(row,dataIndex,newValue){
        const key = this.rowKey;
        row[dataIndex] = newValue;
        this.waitSaveSortInput[row[key]] = newValue;
    }
</script>